﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SpeedTest
{
	public partial class AdminUser : Form
	{
        private Data data = null;
		EditMode mode = EditMode.EditMode;

		public AdminUser(Data data)
		{
			InitializeComponent();
			this.data = data;
		}

		private void AdminUser_Load(object sender, EventArgs e)
		{
			lstUsers.ValueMember = "Value";
            lstUsers.DisplayMember = "Text";
            cmboRole.ValueMember = "Value";
            cmboRole.DisplayMember = "Text";

			LoadRoles();
			DataTable dt = data.GetUsers();
            FillList(dt, dt.Columns["ID"].Ordinal, dt.Columns["UserName"].Ordinal, lstUsers);
			ResetListSelection();
			EnableInput(false);
		}

		private void FillList(DataTable table, int valueIndex, int textIndex, ListBox list)
		{
			if (table != null && table.Rows.Count > 0)
			{
				list.Items.Clear();

				for (int i = 0; i < table.Rows.Count; i++)
				{
					ComboItem ci = new ComboItem();
					ci.Text = table.Rows[i][textIndex].ToString();
					ci.Value = table.Rows[i][valueIndex].ToString();

					list.Items.Add(ci);
				}
			}
		}

        private void FillCombo(DataTable table, int valueIndex, int textIndex, ComboBox combo)
        {
            if (table != null && table.Rows.Count > 0)
            {
                combo.Items.Clear();

                for (int i = 0; i < table.Rows.Count; i++)
                {
                    ComboItem ci = new ComboItem();
                    ci.Text = table.Rows[i][textIndex].ToString();
                    ci.Value = table.Rows[i][valueIndex].ToString();

                    combo.Items.Add(ci);
                }
            }
        }

		private void lstUsers_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadSelectedItem();
        }

        private void LoadRoles()
        {
            DataTable table = data.GetRoles();
            if (table != null)
            {
                FillCombo(table, table.Columns["ID"].Ordinal, table.Columns["Description"].Ordinal, cmboRole);
            }
        }

		private void LoadSelectedItem()
		{
            ComboItem ci = (ComboItem)lstUsers.SelectedItem;
			DataTable table = data.GetUserByID(ci.Value);

			if (table != null && table.Rows.Count > 0)
			{
                txtName.Text = table.Rows[0]["Name"].ToString();
				txtUserName.Text = table.Rows[0]["UserName"].ToString();
                txtPassword.Text = table.Rows[0]["Password"].ToString();
                txtEmailAddr.Text = table.Rows[0]["Email"].ToString();
                SelectRole(table.Rows[0]["RoleID"].ToString());
				bool isActive = Boolean.Parse(table.Rows[0]["Active"].ToString());
				chkActive.Checked = isActive;
			}
		}

        private void SelectRole(string roleID)
        {
            cmboRole.SelectedIndex = -1;
            if (cmboRole.Items.Count > 0)
            {
                for (int i = 0; i < cmboRole.Items.Count; i++)
                {
                    ComboItem ci = (ComboItem)cmboRole.Items[i];
                    if (ci.Value.Equals(roleID))
                    {
                        cmboRole.SelectedIndex = i;
                        break;
                    }
                }

                
            }
        }

		private void EnableInput(bool enable)
		{
			txtName.Enabled = enable;
            txtUserName.Enabled = enable;
            txtPassword.Enabled = enable;
            txtEmailAddr.Enabled = enable;
            cmboRole.Enabled = enable;
			chkActive.Enabled = enable;
			btnSave.Enabled = enable;
			btnCancel.Enabled = enable;

			if (IsPermitted(btnEdit, data.User.Users)) { btnEdit.Enabled = !enable; }
			else { btnEdit.Enabled = false; }
			if (IsPermitted(btnAdd, data.User.Users)) { btnAdd.Enabled = !enable; }
			else { btnAdd.Enabled = false; }
			if (IsPermitted(btnRemove, data.User.Users)) { btnRemove.Enabled = !enable; }
			else { btnRemove.Enabled = false; }
            lstUsers.Enabled = !enable;
        }

		private bool IsPermitted(Button btn, Permissions perm)
		{
			if (btn == btnRemove) { return perm.Delete; }
			if (btn == btnAdd) { return perm.Create; }
			if (btn == btnEdit) { return perm.Edit; }

			return false;
		}

		private void ResetListSelection()
		{
            if (lstUsers.Items.Count > 0)
			{
                lstUsers.SelectedIndex = 0;
			}
		}

		private void btnEdit_Click(object sender, EventArgs e)
		{
            if (lstUsers.SelectedItem != null)
			{
				EnableInput(true);
                txtUserName.Enabled = false;    //cannot edit user name once created.
				txtName.Focus();
			}
		}

		private void btnSave_Click(object sender, EventArgs e)
		{
            if (!ValidateInput()) { return; }

            ComboItem ci = (ComboItem)lstUsers.SelectedItem;
			DataTable table = new DataTable();

            table.Columns.Add("Name");
            table.Columns.Add("UserName");
            table.Columns.Add("Password");
            table.Columns.Add("Email");
			table.Columns.Add("RoleID");
			table.Columns.Add("Active");

			string[] row = new string[6];
			row[0] = txtName.Text;
            row[1] = txtUserName.Text;
            row[2] = txtPassword.Text;
            row[3] = txtEmailAddr.Text;
            ComboItem roleItem = (ComboItem)cmboRole.SelectedItem;
            if (roleItem != null) { row[4] = roleItem.Value; }
            //TODO: Throw error
			if (ci.Value.Equals("1")) { row[5] = "TRUE"; } //The ADMIN user cannot be deactivated.
			else { row[5] = chkActive.Checked ? "TRUE" : "FALSE"; }

			table.Rows.Add(row);

			if (mode == EditMode.EditMode)
			{
				data.UpdateUserByID(table, ci.Value);
			}
			else
			{	//create mode
                if (data.CheckUserNameAvailability(txtUserName.Text))
                {
                    data.InsertUser(table);
                    //reset mode back to default
                    mode = EditMode.EditMode;
                }
                else
                {
                    MessageBox.Show("This user name is already in use. Please try again.");
                    return;
                }

			}

			DataTable dt = data.GetUsers();
            FillList(dt, dt.Columns["ID"].Ordinal, dt.Columns["UserName"].Ordinal, lstUsers);
			ResetListSelection();
			EnableInput(false);
		}

        private bool ValidateInput()
        {
            string requiredFields = String.Empty;

            if (String.IsNullOrEmpty(txtName.Text)) { requiredFields += "Name\n"; }
            if (String.IsNullOrEmpty(txtUserName.Text)) { requiredFields += "User Name\n"; }
            if (String.IsNullOrEmpty(txtPassword.Text)) { requiredFields += "Password\n"; }

            if (!String.IsNullOrEmpty(requiredFields))
            {
                MessageBox.Show("The following required fields are empty\n" + requiredFields, "Error");
                return false;
            }

            return true;
        }

		private void btnCancel_Click(object sender, EventArgs e)
		{
			LoadSelectedItem();
			mode = EditMode.EditMode;	//reset to default
			ResetListSelection();
			EnableInput(false);
		}

		private void btnAdd_Click(object sender, EventArgs e)
		{
			mode = EditMode.CreateMode;
			txtName.Text = String.Empty;
            txtUserName.Text = String.Empty;
            txtPassword.Text = String.Empty;
            txtEmailAddr.Text = String.Empty;
            cmboRole.SelectedIndex = -1;
			chkActive.Checked = true;

			EnableInput(true);
			txtName.Focus();
		}

		private void btnRemove_Click(object sender, EventArgs e)
		{
            if (lstUsers.SelectedItem != null)
			{
                ComboItem ci = (ComboItem)lstUsers.SelectedItem;
				if (ci.Value.Equals("1")) 
				{ 
					MessageBox.Show("This user cannot be deleted");
					return;
				}	//The ADMIN user cannot be deleted.

				DialogResult res = MessageBox.Show("Are you sure you want to delete the user: " + ci.Text, "Confirm Delete", MessageBoxButtons.YesNo);

				if (res == DialogResult.Yes)
				{
					data.DeleteUserByID(ci.Value);
					DataTable dt = data.GetUsers();
                    FillList(dt, dt.Columns["ID"].Ordinal, dt.Columns["UserName"].Ordinal, lstUsers);
					ResetListSelection();

					//TODO: DELETE PLANS, CASES, SUITES, RESULTS, ATTACHMENTS FOR THE RELEASE
				}
			}
		}
	}
}
